package com.sunlands.zlcx.usercenter.common.auth;

import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor;
import org.springframework.security.oauth2.provider.authentication.TokenExtractor;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;

import static com.sunlands.zlcx.usercenter.config.ResourceServerConfig.NO_AUTH_URLS;

/**
 * @author anjl
 * @date 5:04 PM 2019/6/6
 * description:
 */
public class UsersBearerTokenExtractor extends BearerTokenExtractor implements TokenExtractor {
    private AntPathMatcher urlMatcher = new AntPathMatcher();
    @Override
    public Authentication extract(HttpServletRequest request) {
        /**
         * 判断地址是否在不需要权限url中，如果在，直接返回null，不获取token信息
         */
        if (match(request.getRequestURI())) {
            return null;
        }

        String tokenValue = extractToken(request);
        if (tokenValue != null) {
            PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(tokenValue, "");
            return authentication;
        }
        return null;
    }

    public boolean match(String uri){
        return NO_AUTH_URLS.stream().anyMatch(u -> urlMatcher.match(u, uri));
    }
}
